<template>
  <div class="modern-page">
    <div class="login-card modern-card modern-slide-in">
      <div class="login-header modern-card__header">
        <h1 class="login-title modern-text-gradient">SaaS化供应链ERP</h1>
        <p class="login-subtitle">后台管理系统</p>
        <div class="demo-tip modern-glass-light modern-rounded-md">
          <p>🔗 已连接到认证服务，请使用真实账号登录</p>
        </div>
      </div>
      
      <div class="modern-card__content">
        <t-form
          ref="formRef"
          :model="loginForm"
          :rules="rules"
          class="login-form"
          @submit.prevent="handleSubmit"
        >
          <t-form-item name="username">
            <t-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              size="large"
              clearable
              @input="clearValidationErrors"
            >
              <template #prefix-icon>
                <component :is="'UserIcon'" />
              </template>
            </t-input>
          </t-form-item>
          
          <t-form-item name="password">
            <t-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              size="large"
              clearable
              @input="clearValidationErrors"
            >
              <template #prefix-icon>
                <component :is="'LockOnIcon'" />
              </template>
            </t-input>
          </t-form-item>
          
          <!-- 租户选择 -->
          <t-form-item name="tenantId" v-if="showTenantSelect">
            <t-select
              v-model="loginForm.tenantId"
              placeholder="选择租户"
              size="large"
              clearable
              :loading="tenantLoading"
            >
              <template #prefix-icon>
                <component :is="'BuildingIcon'" />
              </template>
              <t-option 
                v-for="tenant in availableTenants" 
                :key="tenant.id" 
                :value="tenant.id" 
                :label="tenant.name"
              >
                {{ tenant.name }}
              </t-option>
            </t-select>
          </t-form-item>
          
          <t-form-item>
            <t-button
              theme="primary"
              size="large"
              block
              :loading="loading"
              class="modern-btn-enhance"
              @click="handleSubmit"
            >
              登录
            </t-button>
          </t-form-item>
        </t-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { MessagePlugin } from 'tdesign-vue-next'
// 图标通过TDesign自动导入，无需手动导入
import { useUserStore } from '@/store/modules/user'

const router = useRouter()
const userStore = useUserStore()

// 表单引用
const formRef = ref()

// 加载状态
const loading = ref(false)

// 表单数据
const loginForm = reactive({
  username: '',
  password: '',
  tenantId: userStore.tenantId || 'default'
})

// 租户相关
const showTenantSelect = ref(false)
const tenantLoading = ref(false)
const availableTenants = ref([])

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 1, message: '密码不能为空', trigger: 'blur' }
  ],
  tenantId: [
    { required: false, message: '请选择租户', trigger: 'change' }
  ]
}

// 清除表单验证错误
const clearValidationErrors = () => {
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  // 先清除之前的验证错误
  clearValidationErrors()
  
  // 手动检查表单数据
  if (!loginForm.username || !loginForm.password) {
    MessagePlugin.warning('请填写完整的登录信息')
    return
  }
  
  // 直接执行登录，跳过TDesign的复杂验证
  await handleLogin()
}

// 处理登录
const handleLogin = async () => {
  loading.value = true
  
  console.log('🚀 开始登录流程...')
  console.log('📝 登录数据:', {
    username: loginForm.username,
    password: '***' + loginForm.password.slice(-2),
    tenantId: loginForm.tenantId
  })
  
  try {
    // 登录前先设置租户ID
    if (loginForm.tenantId) {
      userStore.tenantId = loginForm.tenantId
    }
    
    console.log('📡 调用认证API...')
    await userStore.login({
      username: loginForm.username,
      password: loginForm.password
    })
    
    console.log('✅ 登录成功！')
    MessagePlugin.success('登录成功！')
    
    // 直接跳转到仪表盘
    router.push('/dashboard')
  } catch (error) {
    console.error('登录失败:', error)
    MessagePlugin.error(error.message || '登录失败，请检查输入信息')
  } finally {
    loading.value = false
  }
}

// 获取租户列表
const loadTenants = async () => {
  try {
    tenantLoading.value = true
    const tenants = await userStore.getTenantsList()
    availableTenants.value = tenants
    showTenantSelect.value = tenants.length > 1
  } catch (error) {
    console.error('获取租户列表失败:', error)
    // 如果获取失败，使用默认租户
    showTenantSelect.value = false
  } finally {
    tenantLoading.value = false
  }
}

// 组件挂载时初始化
import { onMounted } from 'vue'

onMounted(async () => {
  // 加载租户列表
  await loadTenants()
  
  console.log('🚀 登录页面初始化完成')
})
</script>

<style lang="scss" scoped>
@use '@/assets/styles/variables.scss' as *;

.login-card {
  width: 100%;
  max-width: 400px;
  margin: 0 auto;
}

.login-title {
  font-size: 1.75rem;
  font-weight: 700;
  margin-bottom: 0.5rem;
  letter-spacing: -0.025em;
}

.login-subtitle {
  font-size: 0.875rem;
  color: var(--modern-text-muted);
  margin-bottom: 1.5rem;
}

.demo-tip {
  margin-top: 1rem;
  padding: 0.75rem 1rem;
  
  p {
    margin: 0;
    font-size: 0.8125rem;
    color: var(--modern-text-secondary);
    text-align: center;
  }
}

.login-form {
  :deep(.t-form-item) {
    margin-bottom: 1.5rem;
  }
  
  :deep(.t-form-item:last-child) {
    margin-bottom: 0;
  }
  
  :deep(.t-input) {
    border-radius: var(--modern-radius-md);
    transition: var(--modern-transition-normal);
    
    &:hover {
      box-shadow: var(--modern-shadow-sm);
    }
    
    &.t-is-focused {
      box-shadow: var(--modern-shadow-md);
    }
  }
  
  :deep(.t-select .t-input) {
    border-radius: var(--modern-radius-md);
  }
  
  :deep(.t-button) {
    border-radius: var(--modern-radius-md);
    height: 3rem;
    font-weight: 600;
    font-size: 1rem;
    background: var(--modern-gradient-primary);
    border: none;
    
    &:hover {
      background: var(--modern-gradient-secondary);
    }
  }
}

// 响应式设计
@media (max-width: 640px) {
  .modern-page {
    padding: 1rem;
  }
  
  .login-card {
    max-width: 100%;
  }
}
</style>
